<template>
	<view class="cart-container">
		<view  style="background-color: #ffffff;">
		  <u-button type="primary" :text="isEditMode?'退出管理':'管理'" :plain="true"  custom-style="width:130rpx; float: right;margin-right:10rpx;height:70rpx" @click="editCart"></u-button>
		</view>
		<u-divider custom-style="margin: 1rpx;"></u-divider>
		<!-- 购物车内容 -->
		<scroll-view scroll-y class="cart-content" :style="{height: scrollHeight + 'px'}" enable-flex>
			<!-- 购物车为空 -->
			<view v-if="cartList.length === 0 && !loadding" class="empty-cart">
				<u-empty mode="car" iconSize="200"></u-empty>
				<view class="empty-text">购物车空空如也~</view>
				<u-button type="primary" shape="circle" @click="goToHome" custom-style="width:200rpx">去逛逛</u-button>
			</view>
			<!-- 购物车商品列表 -->
			<view v-else>
				<u-checkbox-group v-model="goodschecked" @change="checkItem" class="cart-checkbox-group">
					<!-- 商品列表 -->
					<view class="goods-list">
						<view class="goods-item" v-for="(item, index) in cartList" :key="item.id">
							<view class="item-left">
								<u-checkbox :name="item.id" shape="circle"></u-checkbox>
							</view>
							<view class="item-content" @click="goToDetail(item.goods_id)">
								<image class="goods-image" :src="item.goods_image" mode="aspectFill"></image>

								<view class="goods-info">
									<view class="goods-title">{{ item.goods_name }}</view>
									<view class="goods-spec" v-if="item.spec_text">{{ item.spec_text }}</view>
									<view class="goods-price">
										<text class="current-price">¥{{ item.goods_price }}</text>
										<text class="original-price"
											v-if="item.original_price">¥{{ item.original_price }}</text>
									</view>

									<view class="goods-actions">
										<view class="goods-stepper">
											<u-number-box v-model="item.goods_num" :min="1" :max="item.stock" integer
												@change="changeNum(index, $event)"></u-number-box>
										</view>

										<view class="delete-btn" v-if="isEditMode" @click.stop="deleteItem(index)">
											<u-icon name="trash" size="22" color="#fc0004"></u-icon>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</u-checkbox-group>
			</view>
		</scroll-view>

		<!-- 底部结算栏 -->
		<view class="cart-footer" v-if="cartList.length > 0">
			<view class="footer-left">
				<u-checkbox-group v-model="Allchecklist" @change="checkAll">
					<u-checkbox shape="circle" iconSize="18">全选</u-checkbox>
				</u-checkbox-group>
			</view>

			<view class="footer-center" v-if="!isEditMode">
				<view class="total-price">
					合计: <text class="price">¥{{ totalPrice }}</text>
				</view>
				<view class="discount-tips" v-if="totalDiscount > 0">
					已优惠¥{{ totalDiscount }}
				</view>
			</view>

			<view class="footer-right">
				<u-button v-if="!isEditMode" type="error" shape="circle" @click="ConfirmPay" :customStyle="{
					width: '200rpx',
					height: '70rpx',
					margin: '0'
				  }">
					{{ '去结算(' + checkedCount + ')' }}
				</u-button>
				<u-button v-if="isEditMode" type="error" shape="circle" @click="DeleteSelct" :customStyle="{
					width: '200rpx',
					height: '70rpx',
					margin: '0'
				  }">
					删除所选
				</u-button>
			</view>
		</view>

		<!-- 删除确认弹窗 -->
		<u-modal :show="showDeleteModal" title="确认删除" content="确定要删除选中的商品吗？" showCancelButton @confirm="confirmDelete"
			@cancel="showDeleteModal = false"></u-modal>
	</view>
</template>

<script>
	import {
		httpsend
	} from '@/api/api';
	import {
		mapMutations
	} from 'vuex';
	export default {
		components: {

		},
		data() {
			return {
				loadding:false,
				Allchecklist: [],
				allChecked: false,
				scrollHeight: 0,
				isEditMode: false,
				cartList: [],
				recommendList: [],
				showDeleteModal: false,
				deleteIndex: -1
			};
		},
		computed: {
			goodschecked: {
			    get() {
			      return this.cartList.filter(item => item.checked).map(item => item.id);
			    },
			    set(newVal) {
			      // 更新每个商品的 checked 状态
			      this.cartList.forEach(item => {
			        item.checked = newVal.includes(item.id);
			      });
			    }
			  },
			// 选中的商品数量
			checkedCount() {
				return this.cartList.filter(item => item.checked).length;
			},
			// 选中的商品总价
			totalPrice() {
				return this.cartList.reduce((total, item) => {
					return item.checked ? total + (item.goods_price * item.goods_num) : total;
				}, 0).toFixed(2);
			},
			//计算优惠价格
			totalDiscount(){
				return this.cartList.reduce((total, item) => {
					return item.checked ? total + ((item.original_price * item.goods_num)-(item.goods_price * item.goods_num)) : total;
				}, 0).toFixed(2);
			}
		},
		onLoad() {
			this.calcScrollHeight();
			this.loadCartData();
		},
		onShow() {
			// 从其他页面返回时刷新数据
			this.loadCartData();
		},
		methods: {
			...mapMutations(['setorderinfo']),
			// 计算滚动区域高度
			calcScrollHeight() {
				const systemInfo = uni.getSystemInfoSync();
				const navbarHeight = 80; // 导航栏高度
				const footerHeight = 10; // 底部栏高度
				this.scrollHeight = systemInfo.windowHeight - navbarHeight - footerHeight;
			},

			// 加载购物车数据	
			async loadCartData() {
				// 模拟API请求
				this.loadding=true;
				uni.showLoading({
					title: '加载中...'
				});
				try {
					this.logining = true;
					const res = await httpsend('getcartdata');
					if (res?.code === 1) {
						this.cartList = res.data;
					} else {
						this.$api.msg(res.msg);
					}
					this.logining = false;
					this.checkAllStatus();
					uni.hideLoading();
					this.loadding=false;
				} catch (err) {
					this.loadding=false;
					uni.hideLoading();
					console.log('err', err);
				}
			},
			// 检查全选状态
			checkAllStatus() {
				this.allChecked = this.cartList.length > 0 && this.cartList.every(item => item.checked);
			},

			// 切换编辑模式
			editCart() {
				this.isEditMode = !this.isEditMode;
			},

			// 选择单个商品
			checkItem(e) {
				this.checkAllStatus();
			},
			// 全选/取消全选
			checkAll(e) {
				if (e.length > 0) {
					this.goodschecked = this.cartList.map(item => item.id);

				} else {
					this.goodschecked = [];
				}
				this.Allchecklist = e;
			},

			// 修改商品数量
			changeNum(index, value) {
				this.cartList[index].goods_num = value;
				// 这里应该调用API更新服务器数据
				this.updateCartItem(index);
			},

			// 更新购物车商品
			updateCartItem(index) {
				const item = this.cartList[index];
				console.log('更新购物车:', item);
				// 实际项目中调用API更新
			},

			// 删除商品
			deleteItem(index) {
				this.deleteIndex = index;
				this.showDeleteModal = true;
			},

			// 确认删除
			async confirmDelete() {
				try {
					uni.showLoading({
						title: '正在删除...'
					});
					const res = await httpsend('deletecart');
					if (res?.code === 1) {
						if(this.deleteIndex!==-1){
							this.cartList.splice(this.deleteIndex, 1);
						}else{
							this.goodschecked.forEach(k => {
							    const index = this.cartList.findIndex(key => key.id == k);
							    if (index !== -1) { // 确保找到了对应的元素
							        this.cartList.splice(index, 1);
							    }
							});
						}
						this.deleteIndex=-1;
						//后端删除后重新调用查询接口this.loadCartData();
						this.showDeleteModal = false;
						this.checkAllStatus();
						this.isEditMode=false;
					} else {
						this.$api.msg(res.msg);
					}
					uni.hideLoading();
				} catch (err) {
					uni.hideLoading();
					console.log('err', err);
				}
				
			},

			// 删除所选
			DeleteSelct() {
				if (this.goodschecked.length === 0) {
					uni.showToast({
						title: '请选择要删除的商品',
						icon: 'none'
					});
					return;
				}
				this.showDeleteModal = true;
			},
			// 去支付
			async ConfirmPay() {
				if (this.checkedCount === 0) {
					uni.showToast({
						title: '请选择要结算的商品',
						icon: 'none'
					});
					return;
				}
				const selectedItems = this.cartList.filter(item => item.checked);
				this.setorderinfo({
					type:'购物车',
					id:selectedItems.map(row => row.id).join(',')
				});
				
				try {
					const param = {
						cartid: selectedItems.map(row => row.id).join(',')
					};
					//购买创建一个待支付订单
					const res = await httpsend('buynow', JSON.stringify(param));
					if (res?.code === 1) {
						uni.hideLoading();
						uni.navigateTo({
							url: '/pages/order/payment?id=' + res.id
						});
					} else {
						this.$api.msg(res.msg);
					}
				} catch (err) {
					console.log('err', err);
				}
			},
			// 跳转到商品详情
			goToDetail(goodsId) {
				uni.navigateTo({
					url: '/pages/goodsinfo/goodsdetail?id=' + goodsId
				});
			},

			// 跳转到首页
			goToHome() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}
		}
	};
</script>

<style lang="scss">
	.cart-container {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #f7f7f7;

		.topbtn{
			 width: 100rpx !important;
		}
		.cart-content {
			overflow: hidden;
			display: flex;
			flex-direction: column;
			background-color: #f7f7f7;

			/* 重置 u-checkbox-group 的默认样式 */
			.cart-checkbox-group {
				display: block !important;
			}

			.empty-cart {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding-top: 100rpx;

				.empty-text {
					margin: 30rpx 0 40rpx;
					color: #999;
					font-size: 28rpx;
				}
			}

			.goods-list {
				background-color: #fff;
				margin-bottom: 20rpx;
				width: 100%;
				.goods-item {
					width: 100%;
					display: flex;
					padding: 50rpx;
					min-height: 180rpx;
					box-sizing: border-box;
					border-bottom: 1rpx solid #f5f5f5;

					.item-left {
						display: flex;
						align-items: center;
						margin-right: 20rpx;
						min-width: 60rpx;
					}

					.item-content {
						flex: 1;
						display: flex;
						overflow: hidden;

						.goods-image {
							width: 160rpx;
							height: 160rpx;
							border-radius: 8rpx;
							margin-right: 20rpx;
							flex-shrink: 0;
						}

						.goods-info {
							flex: 1;
							display: flex;
							flex-direction: column;
							justify-content: space-between;
							min-width: 0;

							.goods-title {
								font-size: 28rpx;
								color: #333;
								overflow: hidden;
								text-overflow: ellipsis;
								display: -webkit-box;
								-webkit-line-clamp: 2;
								-webkit-box-orient: vertical;
							}

							.goods-spec {
								font-size: 24rpx;
								color: #999;
								margin: 10rpx 0;
							}

							.goods-price {
								.current-price {
									font-size: 32rpx;
									color: #e74c3c;
									font-weight: bold;
								}

								.original-price {
									font-size: 24rpx;
									color: #999;
									text-decoration: line-through;
									margin-left: 10rpx;
								}
							}

							.goods-actions {
								display: flex;
								justify-content: space-between;
								align-items: center;
								margin-top: 20rpx;

								.delete-btn {
									padding: 10rpx;
								}
							}
						}
					}
				}
			}
		}


		.cart-footer {
			position: sticky;
			bottom: 0;
			left: 0;
			right: 0;
			height: 100rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 20rpx;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
			z-index: 10;

			.footer-left {
				display: flex;
				align-items: center;
				flex: 1;

				.u-checkbox {
					margin-right: 10rpx;
				}
			}

			.footer-center {
				flex: 2;
				text-align: right;
				padding-right: 20rpx;

				.total-price {
					font-size: 28rpx;
					color: #333;

					.price {
						color: #e74c3c;
						font-size: 32rpx;
						font-weight: bold;
					}
				}

				.discount-tips {
					font-size: 22rpx;
					color: #999;
				}
			}

			.footer-right {
				flex: 1;
				display: flex;
				justify-content: flex-end;

				.u-btn {
					margin-left: auto;
					width: 200rpx;
					height: 70rpx;
				}
			}
		}

	}
</style>